import java.awt.image.SinglePixelPackedSampleModel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;

public class AntiVirus 
{
	public static final int SIGNATURE_SIZE = 40;

	public static HashMap<String, Signature> substrings;


	public static void main(String[] args)
	{
		substrings = new HashMap<String, Signature>();
		readBadFiles();
	}

	public static void readBadFiles()
	{
		String tmp;
		int i;
		File dir = new File("500Bad");
		for (File child : dir.listFiles()) 
		{
			i=0;
			System.out.println("start read from file: " + child.getName());
			byte[] b= readFile(child.getPath());

			while(i<child.length()-SIGNATURE_SIZE)
			{
				tmp=getSubBytes(b,i,40);
				i+=4;
				if(substrings.containsKey(tmp))
				{
					Signature s=substrings.get(tmp);
					s.counter++;
					s.addToFileNames(child.getName());
				}
				else
				{
					Signature s=new Signature();
					s.addToFileNames(child.getName());
					s.counter++;
					substrings.put(tmp, s);
				}
			}
		}

	}

	private static String getSubBytes(byte[] b, int off, int length) {
		String ans = "";
		for (int i = 0; i < length; i++) {
			ans += (char)b[off+i];
		}
		return ans;
	}

	public static byte[] readFile(String input)
	{
		FileInputStream file;
		int n = 0, off = 0;
		byte[] b = new byte[1024 * 1024];

		try 
		{
			file = new FileInputStream(new File(input));
			while(n != -1)
			{
				n=file.read(b, off, 500);
				off += n;
			}

			file.close();
		} 
		catch (IOException e) {
			System.out.println("Error reading file: " + input);
			System.exit(1);
			return b;
		}
		return b;
	}

	public static String getSubString(String inputFilename, int numOfBytes, int start){
		String ans = "";
		FileInputStream file;
		int n, off = 0;
		try 
		{
			file = new FileInputStream(new File(inputFilename));
			while ((n = file.read()) != -1)
			{
				off ++;
				if (off < start)
					continue;
				ans = ans + (char)n;
				if (ans.length() == numOfBytes)
					break;
			}
			file.close();
		} 
		catch (IOException e) {
			System.out.println("Error reading file: " + inputFilename);
			System.exit(1);
			return ans;
		}
		return ans;
	}

}
